package com.party.mobile.biz.order;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.*;
import com.party.core.exception.BusinessException;
import com.party.core.exception.OrderException;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.ActStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.city.City;
import com.party.core.model.copartner.BrokerageItem;
import com.party.core.model.crowdfund.*;
import com.party.core.model.distributor.DistributorRelationType;
import com.party.core.model.goods.Goods;
import com.party.core.model.goods.GoodsCoupons;
import com.party.core.model.member.*;
import com.party.core.model.order.*;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.city.ICityService;
import com.party.core.service.count.IDataCountService;
import com.party.core.service.crowdfund.*;
import com.party.core.service.crowdfund.biz.CrowdfundReviseBizService;
import com.party.core.service.crowdfund.biz.ProjectDetailCountBizService;
import com.party.core.service.distributor.IDistributorCountService;
import com.party.core.service.goods.IGoodsCouponsService;
import com.party.core.service.goods.IGoodsService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.member.biz.MemberPersonalCountBizService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.order.IOrderFormSubInfoService;
import com.party.mobile.biz.analyze.MemberCopartnerDetailBizService;
import com.party.mobile.biz.analyze.MemberMerchantDetailBizService;
import com.party.mobile.biz.copartner.BrokerageBizService;
import com.party.mobile.biz.crowdfund.ProjectBizService;
import com.party.mobile.biz.crowdfund.SupportBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.distributor.DistributorBizService;
import com.party.mobile.biz.mall.MallOrderBizService;
import com.party.mobile.web.dto.activity.input.ApplyInput;
import com.party.mobile.web.dto.crowdfund.input.StatisticsInput;
import com.party.mobile.web.dto.crowdfund.input.SupportStatisticsInput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.order.Output.ActOrderDetailOutput;
import com.party.mobile.web.dto.order.Output.OrderDetailOutput;
import com.party.mobile.web.dto.order.Output.OrderOutput;
import com.party.mobile.web.dto.order.input.BookOrderInput;
import com.party.pay.model.query.TradeStatus;
import com.party.pay.service.pay.PayOrderBizService;
import com.party.synthesis.IProjectMessageService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * 订单逻辑业务服务
 * party
 * Created by wei.li
 * on 2016/10/8 0008.
 */

@Service
public class OrderBizService {

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private IGoodsCouponsService goodsCouponsService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IMemberActService memberActService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private CurrentUserBizService currentUserBizService;

    @Autowired
    private ICityService cityService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private ITargetProjectService targetProjectService;

    @Autowired
    private MessageOrderBizService messageOrderBizService;

    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;

    @Autowired
    private MemberMerchantDetailBizService memberMerchantDetailBizService;

    @Autowired
    private MemberPersonalCountBizService memberPersonalCountBizService;

    @Autowired
    private MallOrderBizService mallOrderBizService;

    @Autowired
    private ProjectDetailCountBizService projectDetailCountBizService;

    @Autowired
    private CrowdfundReviseBizService crowdfundReviseBizService;

    @Autowired
    private BrokerageBizService brokerageBizService;

    @Autowired
    private IAnalyzeService analyzeService;

    @Autowired
    private IEventGradationService eventGradationService;

    @Autowired
    private IProjectGradationService projectGradationService;

    // 预约成功短信模板
    @Value("#{sms['success.member.template']}")
    private String memberTemplate;

    @Value("#{sms['success.member.crowdfund.template']}")
    private String cowdfundTemplate;

    // 预约成功短信模板
    @Value("#{sms['success.third.template']}")
    private String thirdTemplate;

    @Autowired
    private IDataCountService dataCountService;

    @Autowired
    private OrderTradeBizService orderTradeBizService;

    @Autowired
    private PayOrderBizService payOrderBizService;

    @Autowired
    private ProjectBizService projectBizService;

    @Autowired
    private IPartnerMemberService partnerMemberService;

    @Autowired
    private IDistributorCountService distributorCountService;

    @Autowired
    private SupportBizService supportBizService;

    @Autowired
    private DistributorBizService distributorBizService;

    @Autowired
    private IOrderFormSubInfoService orderFormSubInfoService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private IProjectInfoGradationService projectInfoGradationService;

    @Autowired
    private IProjectMessageService projectMessageService;

    @Autowired
    private IMemberGroupService memberGroupService;

    protected static Logger logger = LoggerFactory.getLogger(OrderBizService.class);


    private static final int SUPPORT_IS_PAY = 1;


    public OrderOutput getOrderById(String orderId, HttpServletRequest request) {
        OrderForm orderForm = orderFormService.get(orderId);
        //验证标准商品订单数据
        if (null == orderForm) {
            throw new BusinessException(PartyCode.ORDER_FORM_NOT_EXIT, "订单不存在");
        }

        //验证标准商品订单是否属于当前登录用户
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        if (!currentUser.getId().equals(orderForm.getMemberId())) {
            throw new BusinessException(PartyCode.ORDER_FORM_DATA_ERROR, "订单数据错误，下单人与当前用户不是同一人");
        }
        OrderOutput orderOutput = OrderOutput.transform(orderForm);
        if (orderForm.getType().equals(OrderType.ORDER_ACTIVITY.getCode())
                || OrderType.ORDER_COURSE.getCode().equals(orderForm.getType())) {
            Activity act = activityService.get(orderForm.getGoodsId());
            orderOutput.setDescription(act.getTitle());
            MemberAct myMemberAct = memberActService.getMyAct(currentUser.getId(), act.getId());
            if (null != myMemberAct) {
                orderOutput.setMemberActId(myMemberAct.getId());
            }
        } else if (orderForm.getType().equals(OrderType.ORDER_NOMAL.getCode())) {
            Goods goods = goodsService.get(orderForm.getGoodsId());
            orderOutput.setDescription(goods.getTitle());
        }
        return orderOutput;
    }

    /**
     * 同行者下单
     *
     * @param orderForm  订单信息
     * @param object     支付信息
     * @param paymentWay 支付方式
     * @param
     * @throws OrderException 订单异常
     */
    @Transactional
    public void payOrder(OrderForm orderForm, Object object, Integer paymentWay) throws OrderException {

        // 修改订单状态
        orderForm.setIsPay(PaymentState.IS_PAY.getCode());
        orderForm.setPaymentWay(paymentWay);
        orderForm.setStatus(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode());
        orderForm.setUpdateDate(new Date());
        orderFormService.update(orderForm);

        // 如果是活动支付成功，设置活动报名状态
        if (orderForm.getType().equals(OrderType.ORDER_ACTIVITY.getCode())
                || OrderType.ORDER_COURSE.getCode().equals(orderForm.getType())) {
            MemberAct dbMemberAct = memberActService.findByOrderId(orderForm.getId());
            if (dbMemberAct != null) {
                dbMemberAct.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode()); // 已支付，报名成功
                dbMemberAct.setPayStatus(MemberAct.PAY_STATUS_YES);
                memberActService.update(dbMemberAct);
            }
        }

        // 如果是活动支付成功，设置活动报名状态
        if (orderForm.getType().equals(OrderType.ORDER_ACTIVITY.getCode())) {
            MemberAct dbMemberAct = memberActService.findByOrderId(orderForm.getId());
            if (dbMemberAct != null) {

                // 处理众筹主订单
                if (!TradeStatus.ZCXM.getCode().equals(orderForm.getMerchantId())) {
                    try {
                        memberMerchantDetailBizService.updateOrderNum(orderForm.getInitiatorId(), orderForm.getPayment());
                    } catch (Exception e) {
                        logger.error("实时更新机构订单统计数异常", e);
                    }

                    try {
                        memberMerchantDetailBizService.updateApplyNum(orderForm.getInitiatorId());
                    } catch (Exception e) {
                        logger.error("实时更新机构报名统计数异常", e);
                    }

                    // 实时更新活动报名金额
                    try {
//                        memberPersonalCountBizService.updateActivityNumMoney(orderForm.getInitiatorId(), orderForm.getMemberId(), orderForm.getPayment(), true);
                        PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(orderForm.getInitiatorId(), orderForm.getMemberId());
                        memberPersonalCountBizService.countOne(partnerMember);
                    } catch (Exception e) {
                        logger.error("实时更新活动报名金额/数量失败", e);
                    }
                } else {
                    // 普通活动
                    Activity activity = activityService.get(dbMemberAct.getActId());
                    activity.setOrderNum(getActivityOrderNum(activity.getOrderNum()));
                    activity.setTotalMoney(getActivityTotalMoney(activity.getTotalMoney(), orderForm.getPayment()));
                    activityService.update(activity);
                }
            }
        }

        //持久化交易信息
        if (object != null) {
            orderTradeBizService.save(orderForm, object, paymentWay);
        }

        //如果是众筹订单
        if (orderForm.getType().equals(OrderType.ORDER_CROWD_FUND.getCode())) {
            this.paySupport(orderForm);
            return;
        }

        // 如果是商城订单
        if (orderForm.getType().equals(OrderType.ORDER_MALL.getCode())) {
            mallOrderBizService.payMall(orderForm.getId());
            return;
        }

        if (OrderType.ORDER_ACTIVITY.getCode().equals(orderForm.getType())
                || OrderType.ORDER_COURSE.getCode().equals(orderForm.getType())) {
            //只有活动有销售量
            activityService.countSales(orderForm.getGoodsId(), orderForm.getPayment());
        }
    }

    /**
     * 订单发码
     *
     * @param orderForm 订单信息
     */
    public void sendCode(OrderForm orderForm) {

        List<GoodsCoupons> goodsCouponss = goodsCouponsService.findByOrderId(orderForm.getId());
        if (goodsCouponss.size() == 0) {
            List<String> verifyCodeList = payOrderBizService.getVerifyCode(orderForm.getId(), orderForm.getUnit());
            for (String verifyCode : verifyCodeList) {

                //生成核销码
                GoodsCoupons goodsCoupons = new GoodsCoupons();
                goodsCoupons.setOrderId(orderForm.getId());
                goodsCoupons.setMemberId(orderForm.getMemberId());
                goodsCoupons.setGoodsId(orderForm.getGoodsId());
                goodsCoupons.setVerifyCode(verifyCode);
                goodsCoupons.setType(orderForm.getType());
                goodsCouponsService.insert(goodsCoupons);
            }
        }
        // 发送推送消息
        try {
            messageOrderBizService.send(orderForm.getId());
        } catch (Exception e) {
            logger.error("下单消息推送异常", e);
        }
    }

    /**
     * 订单预定
     *
     * @param input    输入视图
     * @param memberId 会员主键
     * @return 订单信息
     */
    @Transactional
    public OrderDetailOutput bookOrder(BookOrderInput input, String memberId) throws BusinessException {
        OrderForm orderForm = new OrderForm();
        orderForm.setMemberId(memberId);
        Goods goods = goodsService.get(input.getGoodsId());
        if (null == goods) {
            throw new BusinessException(PartyCode.GOODS_UNEXIST, "商品不存在");
        }

        orderForm.setGoodsId(input.getGoodsId());
        orderForm.setUnit(input.getUnit());
        orderForm.setLinkman(input.getLinkman());
        orderForm.setPhone(input.getPhone());
        orderForm.setType(input.getType());
        orderForm.setStatus(input.getStatus());
        orderForm.setIsPay(PaymentState.NO_PAY.getCode());
        orderForm.setRemarks(input.getRemarks());
        orderForm.setTitle(goods.getTitle());
        //如果是分享商品 统计
        if (!Strings.isNullOrEmpty(input.getStoreGoodsId())) {
            orderForm.setStoreGoodsId(input.getStoreGoodsId());
        }
        double payment = BigDecimalUtils.mul(goods.getPrice(), input.getUnit());
        double payment2 = BigDecimalUtils.round(payment, 2);
        orderForm.setPayment((float) payment2);
        orderForm.setInitiatorId(goods.getMemberId());
        orderFormService.insert(orderForm);

        Member member = memberService.get(orderForm.getMemberId());
        try {
            MemberGroup initiator = memberGroupService.get(orderForm.getInitiatorId());

            OrderFormSubInfo formSubInfo = new OrderFormSubInfo();
            formSubInfo.setOrderId(orderForm.getId());
            if (null != member) {
                formSubInfo.setAuthorLogo(member.getLogo());
                formSubInfo.setAuthorName(member.getRealname());
            }
            if (null != initiator) {
                formSubInfo.setInitiatorLogo(initiator.getLogo());
                formSubInfo.setInitiatorName(initiator.getRealname());
            }
            orderFormSubInfoService.insert(formSubInfo);
        } catch (Exception e) {
            logger.error("保存订单附属信息异常", e);
        }

        if (goods.getLimitNum() != null) {
            // 库存减下单份数
            goods.setLimitNum(goods.getLimitNum() - input.getUnit());
            goodsService.update(goods);
        }

        //输出商品订单信息
        OrderDetailOutput output = OrderDetailOutput.transform(orderForm);

        //设置城市
        City city = cityService.get(goods.getCityId());
        if (null != city) {
            output.setCityName(city.getName());
        }
        output.setAreaName(goods.getArea());
        output.setPlace(goods.getPlace());

        //设置商品信息
        output.setDescription(goods.getTitle());
        output.setLogo(goods.getPicsURL());
        output.setStartTime(goods.getStartTime());
        output.setEndTime(goods.getEndTime());

        //获取活动提供方
        if (null != member) {
            output.setThirdPartyName(member.getRealname());
            output.setTelephone(member.getMobile());
        }
        return output;
    }

    public BookOrderInput createBookOrder(ApplyInput applyInput) {
        BookOrderInput bookOrderInput = new BookOrderInput();
        bookOrderInput.setType(applyInput.getOrderType());
        bookOrderInput.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());// 更改为“待支付”状态
        bookOrderInput.setPayment(applyInput.getPayment());
        bookOrderInput.setGoodsId(applyInput.getId());
        bookOrderInput.setUnit(1);
        bookOrderInput.setLinkman(applyInput.getRealname());
        bookOrderInput.setPhone(applyInput.getMobile());
        bookOrderInput.setStoreGoodsId(applyInput.getStoreGoodsId());
        return bookOrderInput;
    }

    /**
     * 订单预定
     *
     * @param input    输入视图
     * @param memberId 会员主键
     * @return 订单信息
     */
    @Transactional
    public OrderOutput bookActOrder(BookOrderInput input, String memberId) throws BusinessException {
        OrderForm orderForm = new OrderForm();
        orderForm.setMemberId(memberId);
        Activity activity = activityService.get(input.getGoodsId());
        if (null == activity) {
            throw new BusinessException(PartyCode.ACTIVITY_UNEXIST, "活动不存在");
        }
        if (StringUtils.isNotEmpty(input.getMerchantId())) {
            orderForm.setMerchantId(input.getMerchantId());
        }
        orderForm.setGoodsId(input.getGoodsId());
        orderForm.setUnit(input.getUnit());
        orderForm.setLinkman(input.getLinkman());
        orderForm.setPhone(input.getPhone());
        orderForm.setType(input.getType());
        orderForm.setStatus(input.getStatus());
        orderForm.setIsPay(PaymentState.NO_PAY.getCode());
        //如果是分享商品 统计
        if (!Strings.isNullOrEmpty(input.getStoreGoodsId())) {
            orderForm.setStoreGoodsId(input.getStoreGoodsId());
        }

        if (input.getPayment() == null) {
            input.setPayment(activity.getPrice());
        }

        double payment = BigDecimalUtils.mul(input.getPayment(), input.getUnit());
        double payment2 = BigDecimalUtils.round(payment, 2);
        orderForm.setPayment((float) payment2);
        orderForm.setTitle(activity.getTitle());
        orderForm.setInitiatorId(activity.getMember());
        orderFormService.insert(orderForm);

        try {
            Member member = memberService.get(orderForm.getMemberId());
            MemberGroup initiator = memberGroupService.get(orderForm.getInitiatorId());

            OrderFormSubInfo formSubInfo = new OrderFormSubInfo();
            formSubInfo.setOrderId(orderForm.getId());
            if (null != member) {
                formSubInfo.setAuthorLogo(member.getLogo());
                formSubInfo.setAuthorName(member.getRealname());
            }
            if (null != initiator) {
                formSubInfo.setInitiatorLogo(initiator.getLogo());
                formSubInfo.setInitiatorName(initiator.getRealname());
            }
            orderFormSubInfoService.insert(formSubInfo);
        } catch (Exception e) {
            logger.error("保存订单附属信息异常", e);
        }

        //输出视图
        OrderOutput orderOutput = OrderOutput.transform(orderForm);
        orderOutput.setDescription(activity.getTitle());
        orderOutput.setLogo(activity.getPic());


        //判断是否是多场活动
        if (StringUtils.isEmpty(activity.getEventId())) {
            orderOutput.setStartTime(activity.getStartTime());
            orderOutput.setEndTime(activity.getEndTime());
        }


        return orderOutput;
    }

    /**
     * 待审核活动列表，取活动报名数据
     *
     * @param memberAct
     * @param page
     * @return
     */
    public List<OrderOutput> listOrderOutput(MemberAct memberAct, Page page) {
        List<MemberAct> dbList = memberActService.listPage(memberAct, page);
        if (!CollectionUtils.isEmpty(dbList)) {
            List<OrderOutput> orderOutputList = LangUtils.transform(dbList, input -> {
                OrderOutput orderOutput = new OrderOutput();
                orderOutput.setStatus(OrderStatus.ORDER_STATUS_IN_REVIEW.getCode()); // 審核中
                orderOutput.setUnit(1);
                orderOutput.setPayment(input.getPayment());
                Activity activity = activityService.get(input.getActId());
                if (null != activity) {
                    //活动信息
                    orderOutput.setDescription(activity.getTitle());
                    orderOutput.setLogo(activity.getPic());
                    orderOutput.setStartTime(activity.getStartTime());
                    orderOutput.setEndTime(activity.getEndTime());
                    orderOutput.setGoodsId(activity.getId());
                }
                return orderOutput;
            });
            return orderOutputList;
        }
        return Collections.EMPTY_LIST;
    }

    /**
     * 订单列表
     *
     * @param orderForm 订单条件过滤实体
     * @param page
     * @param status
     * @return 订单信息
     */
    @Transactional
    public List<OrderOutput> listOrderOutput(OrderForm orderForm, Page page, Set<Integer> status) {

        List<OrderForm> dbList = orderFormService.listPage(orderForm, page, status);

        if (!CollectionUtils.isEmpty(dbList)) {
            List<OrderOutput> orderOutputList = LangUtils.transform(dbList, input -> {
                OrderOutput orderOutput = OrderOutput.transform(input);

                //设置订单的商品信息或活动信息
                if (input.getType().equals(OrderType.ORDER_NOMAL.getCode())) {
                    Goods goods = goodsService.get(input.getGoodsId());
                    if (null != goods) {
                        //商品信息
                        orderOutput.setDescription(goods.getTitle());
                        orderOutput.setLogo(goods.getPicsURL());
                        orderOutput.setStartTime(goods.getStartTime());
                        orderOutput.setEndTime(goods.getEndTime());
                    }
                } else if (input.getType().equals(OrderType.ORDER_ACTIVITY.getCode())
                        || OrderType.ORDER_COURSE.getCode().equals(input.getType())) {
                    Activity activity = activityService.get(input.getGoodsId());
                    if (null != activity) {
                        //活动信息
                        orderOutput.setDescription(activity.getTitle());
                        orderOutput.setLogo(activity.getPic());
                        orderOutput.setStartTime(activity.getStartTime());
                        orderOutput.setEndTime(activity.getEndTime());
                    }
                }
                return orderOutput;
            });
            return orderOutputList;
        }
        return Collections.EMPTY_LIST;

    }


    public OrderDetailOutput getGoodsOrderDetail(String orderId, HttpServletRequest request) throws BusinessException {
        OrderForm orderForm = orderFormService.get(orderId);
        //验证标准商品订单数据
        if (null == orderForm) {
            throw new BusinessException(PartyCode.ORDER_FORM_NOT_EXIT, "订单不存在");
        } else if (!orderForm.getType().equals(OrderType.ORDER_NOMAL.getCode())) {
            throw new BusinessException(PartyCode.ORDER_FORM_GOODS_NOT_EXIT, "订单数据错误，商品或活动不存在");
        }

        //验证标准商品订单是否属于当前登录用户
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        if (!currentUser.getId().equals(orderForm.getMemberId())) {
            throw new BusinessException(PartyCode.ORDER_FORM_DATA_ERROR, "订单数据错误，下单人与当前用户不是同一人");
        }

        //验证标准商品订单关联的商品数据是否存在
        Goods goods = goodsService.get(orderForm.getGoodsId());
        if (null == goods) {
            throw new BusinessException(PartyCode.ORDER_FORM_GOODS_NOT_EXIT, "订单数据错误，商品或活动不存在");
        }

        //输出标准商品订单信息
        OrderDetailOutput output = OrderDetailOutput.transform(orderForm);

        //设置城市
        City city = cityService.get(goods.getCityId());
        if (null != city) {
            output.setCityName(city.getName());
        }
        output.setAreaName(goods.getArea());
        output.setPlace(goods.getPlace());

        //设置商品信息
        output.setDescription(goods.getTitle());
        output.setLogo(goods.getPicsURL());
        output.setStartTime(goods.getStartTime());
        output.setEndTime(goods.getEndTime());

        //获取活动提供方
        MemberGroup member = memberGroupService.get(goods.getMemberId());
        if (null != member) {
            output.setThirdPartyName(member.getRealname());
            output.setTelephone(member.getMobile());
        }

        // 已支付
        if (orderForm.getIsPay().equals(PaymentState.IS_PAY.getCode())) {
            //设置核销码
            GoodsCoupons goodsCoupons = new GoodsCoupons();
            goodsCoupons.setGoodsId(goods.getId());
            goodsCoupons.setOrderId(orderForm.getId());
            goodsCoupons.setMemberId(currentUser.getId());

            List<GoodsCoupons> goodsCouponseslist = goodsCouponsService.list(goodsCoupons);

            List<String> list = new ArrayList<>();
            for (int i = 0; i < goodsCouponseslist.size(); i++) {
                list.add(goodsCouponseslist.get(i).getVerifyCode());
            }
            output.setConsumerCode(list);
        }

        return output;
    }

    /**
     * 根据订单ID获取活动详情
     *
     * @param orderId 订单ID
     * @param request
     * @return
     * @throws BusinessException
     */
    public ActOrderDetailOutput getActOrderDetail(String orderId, HttpServletRequest request) throws BusinessException {
        OrderForm orderForm = orderFormService.get(orderId);
        //验证活动订单数据
        if (null == orderForm) {
            throw new BusinessException(PartyCode.ORDER_FORM_NOT_EXIT, "订单不存在");
        } else if (!orderForm.getType().equals(OrderType.ORDER_ACTIVITY.getCode())) {
            throw new BusinessException(PartyCode.ORDER_FORM_GOODS_NOT_EXIT, "订单数据错误，商品或活动不存在");
        }

        //验证活动订单是否属于当前登录用户
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        if (!currentUser.getId().equals(orderForm.getMemberId())) {
            throw new BusinessException(PartyCode.ORDER_FORM_DATA_ERROR, "订单数据错误，下单人与当前用户不是同一人");
        }

        //验证活动订单关联的商品数据是否存在
        Activity activity = activityService.get(orderForm.getGoodsId());
        if (null == activity) {
            throw new BusinessException(PartyCode.ORDER_FORM_GOODS_NOT_EXIT, "订单数据错误，商品或活动不存在");
        }

        //输出活动订单信息
        ActOrderDetailOutput output = ActOrderDetailOutput.transform(orderForm);

        //设置城市
        City city = cityService.get(activity.getCityId());
        if (null != city) {
            output.setCityName(city.getName());
        }
        output.setAreaName(activity.getArea());
        output.setPlace(activity.getPlace());

        //设置活动信息
        output.setDescription(activity.getTitle());
        output.setLogo(activity.getPic());
        output.setStartTime(activity.getStartTime());
        output.setEndTime(activity.getEndTime());
        //设置活动报名信息
        MemberAct dbMemberAct = memberActService.getMyAct(currentUser.getId(), activity.getId());
        if (null != dbMemberAct) {
            output.setMeberActId(dbMemberAct.getId());
            output.setActStatus(dbMemberAct.getCheckStatus());
//            output.setStatus(dbMemberAct.getCheckStatus());
        }


        //获取活动提供方
        MemberGroup member = memberGroupService.get(activity.getMember());
        if (null != member) {
            output.setThirdPartyName(member.getRealname());
            output.setTelephone(member.getMobile());
        }

        //设置核销码
        GoodsCoupons goodsCoupons = new GoodsCoupons();
        goodsCoupons.setGoodsId(activity.getId());
        goodsCoupons.setOrderId(orderForm.getId());
        goodsCoupons.setMemberId(currentUser.getId());

        List<GoodsCoupons> goodsCouponseslist = goodsCouponsService.list(goodsCoupons);

        List<String> list = new ArrayList<>();
        for (int i = 0; i < goodsCouponseslist.size(); i++) {
            list.add(goodsCouponseslist.get(i).getVerifyCode());
        }
        output.setConsumerCode(list);

        return output;
    }

    /**
     * 获取活动订单详情(New)
     *
     * @param orderId 数据可能是订单id，可能是活动报名id
     * @return
     */
    public ActOrderDetailOutput getActOrderDetail3(String orderId, String memberActId) throws BusinessException {
        OrderForm orderForm = null;
        MemberAct newMemberAct = null;
        MemberAct memberAct = null;
        if (StringUtils.isNotEmpty(orderId)) {
            orderForm = orderFormService.get(orderId);
            if (StringUtils.isEmpty(memberActId)) {
                memberActId = orderId;
            }
            newMemberAct = memberActService.findByOrderId(orderId);
        }
        if (StringUtils.isNotEmpty(memberActId)) {
            memberAct = memberActService.get(memberActId);
        }
        if (null == memberAct && null != newMemberAct) {
            memberAct = newMemberAct;
        }

        if (orderForm == null && memberAct == null) {
            throw new BusinessException(PartyCode.ORDER_FORM_NOT_EXIT, "订单不存在");
        }

        try {
            if (orderForm != null) {
                ActOrderDetailOutput output = outputByOrderForm(orderForm);
                return output;
            } else if (memberAct != null) {
                ActOrderDetailOutput output = outputByMemberAct(memberAct);
                return output;
            }
        } catch (Exception e) {
            logger.error("订单详情异常", e);
        }
        return null;
    }

    /**
     * 获取活动订单详情(New)
     *
     * @param orderId 数据可能是订单id，可能是活动报名id
     * @return
     */
    public ActOrderDetailOutput getActOrderDetail2(String orderId, String memberActId) throws BusinessException {
        OrderForm orderForm = orderFormService.get(orderId);
        if (StringUtils.isEmpty(memberActId)) {
            memberActId = orderId;
        }
        MemberAct memberAct = memberActService.get(memberActId);
        MemberAct newMemberAct = memberActService.findByOrderId(orderId);

        memberAct = memberAct == null ? newMemberAct : memberAct;
        if (orderForm == null && memberAct == null) {
            throw new BusinessException(PartyCode.ORDER_FORM_NOT_EXIT, "订单不存在");
        }

        try {
            if (orderForm != null) {
                ActOrderDetailOutput output = outputByOrderForm(orderForm);
                return output;
            } else if (memberAct != null) {
                ActOrderDetailOutput output = outputByMemberAct(memberAct);
                return output;
            }
        } catch (Exception e) {
            logger.error("订单详情异常：{}", e);
        }
        return null;
    }

    /**
     * 处理支付业务
     *
     * @param orderId
     * @param from
     * @throws Exception
     */
    @Transactional(readOnly = false)
    public void updatePayBusiness(String orderId, String from) throws Exception {
        payOrderBizService.freeOrder(orderId, from);
        payOrderBizService.updateJoinNum(orderId);
    }

    /**
     * 处理支付业务
     *
     * @param orderForm
     * @param object
     * @param paymentWay
     */
    public void updatePayBusiness(OrderForm orderForm, Object object, Integer paymentWay) {

        //如果是众筹订单
        try {
            if (OrderType.ORDER_CROWD_FUND.getCode().equals(orderForm.getType())) {
                Support support = supportService.findByOrderId(orderForm.getId());
                Project project = projectService.get(support.getProjectId());
                project.setFavorerNum(project.getFavorerNum() + 1);
                projectService.update(project);
            }
        } catch (Exception e) {
            logger.error("修改project众筹支持人数异常", e);
        }

        //多场活动
        new Thread(() -> {
            try {
                updateMultipleActivity(orderForm);
            } catch (Exception e) {
                logger.error("多场活动支付回调更新数据异常", e);
            }
        }).start();

        //订单支付
        long start,end;
        start = System.currentTimeMillis();
        payOrder(orderForm, object, paymentWay);
        end = System.currentTimeMillis();
        logger.info(orderForm.getId()+"Run Time :{}", (end - start) + "(ms)");
        payOrderBizService.updateJoinNum(orderForm.getId());
        // 统计
        dealPayCountBusiness(orderForm);
    }

    /**
     * 处理支付后统计的业务
     *
     * @param orderForm
     */
    public void dealPayCountBusiness(OrderForm orderForm) {
        try {
            // 众筹支持订单
            if (OrderType.ORDER_CROWD_FUND.getCode().equals(orderForm.getType())) {
                Support support = supportService.findByOrderId(orderForm.getId());
                Project project = projectService.get(support.getProjectId());
                logger.info("project::" + project);
                TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
                Activity activity = activityService.get(targetProject.getTargetId());

                try {
                    crowdfundReviseBizService.reviseOne(project.getId());
                    crowdfundReviseBizService.targetReviseOne(targetProject.getTargetId());
                    support = supportService.findByOrderId(orderForm.getId());
                    project = projectService.get(support.getProjectId());
                } catch (Exception e) {
                    logger.error("支持完成后, 立即校验众筹和活动数据异常", e);
                }
                final String pid = project.getId();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Date now = new Date();
                            Date startDate = DateUtils.addDay(now, -6);
                            //最近七天的众筹金额
                            Float sevenDaysNum = supportService.countBySupportDate(DateUtils.formatDate(startDate),
                                    DateUtils.formatDate(now), pid);
                            Analyze analyze = analyzeService.findByTargetId(pid);
                            if (null != analyze) {
                                analyze.setSevenDaysNum(sevenDaysNum);
                                analyzeService.update(analyze);
                                logger.info("支持者支付成功后更新analyze中的sevenDaysNum字段成功");
                            }
                        } catch (Exception e) {
                            logger.error("支持完成后, 更新analyze数据异常", e);
                        }
                    }
                }).start();

                //判断是否是多场活动
                CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());

                //支持完成后,更新project表中的useTime
                try {
                    logger.info("project.getId:" + project.getId() + "====" + project.getUseTime());
                    long now = DateUtils.getTodayDate().getTime();
                    long createDate = project.getCreateDate().getTime();
                    if (project.getIsSuccess() == 0) {
                        project.setUseTime(now - createDate);
                    } else if (project.getIsSuccess() == 1) {
                        if (project.getLastSupportDate() != null) {
                            project.setUseTime(project.getLastSupportDate().getTime() - createDate);
                        }
                    }
                    if (project.getUseTime() != null) {
                        projectService.update(project);
                        logger.info("-----project.getId:" + project.getId() + "====" + project.getUseTime());
                    }
                } catch (Exception e) {
                    logger.error("支持完成后, 更新project表中的useTime异常", e);
                }


                try {
                    projectDetailCountBizService.countProjectSomeDay(project.getId(), support.getCreateDate());
                } catch (Exception e) {
                    logger.error("众筹统计分析数据更新异常", e);
                }

                if (Constant.IS_SUCCESS.equals(project.getIsSuccess()) && YesNoStatus.NO.getCode() == crowdfundEvent.getIsMultiple()) {

                    //如果众筹成功了, 就发码
                    try {
                        OrderForm mainOrder = orderFormService.get(targetProject.getOrderId());
                        sendCode(mainOrder);
                    } catch (Exception e) {
                        logger.error("众筹成功后发码异常", e);
                    }

                    // 如果众筹成功了, 修改机构成功数
                    try {
                        memberMerchantDetailBizService.updateSuccessNum(activity.getMemberId());
                    } catch (Exception e) {
                        logger.error("众筹成功后更新机构成功数异常", e);
                    }
                    final String projectId = project.getId();
                    final String orderMemberId = project.getAuthorId();
                    if (project.getPayType() == 0) {

                        //在微信公众号上给众筹者推送成功海报
                        final String activityMemberId = activity.getMember();
                        new Thread(() -> {
                            try {
                                messageOrderBizService.raiseSuccessfulPostersSend(projectId, orderMemberId, activityMemberId);
                            } catch (Exception e) {
                                logger.error("推送成功海报失败", e);
                            }
                        }).start();

                    }

                    // 插入分销佣金记录
                    new Thread(() -> {
                        try {
                            brokerageBizService.insertBrokerageItem(projectId, activity.getId(), BrokerageItem.TYPE_CROWDFUND, orderMemberId);
                        } catch (Exception e) {
                            logger.error("插入分销佣金记录异常", e);
                        }
                    }).start();
                }

                try {
                    SupportStatisticsInput supportStatisticsInput = new SupportStatisticsInput();
                    supportStatisticsInput.setProjectId(project.getId());
                    supportStatisticsInput.setSupportId(orderForm.getId());
                    supportStatisticsInput.setPayment(orderForm.getPayment());
                    supportBizService.statistics(supportStatisticsInput);
                } catch (Exception e) {
                    logger.error("支持数据统计分销数据异常", e);
                }


            } else if (OrderType.ORDER_ACTIVITY.getCode().equals(orderForm.getType())
                    || OrderType.ORDER_COURSE.getCode().equals(orderForm.getType())) {
                MemberAct memberAct = memberActService.findByOrderId(orderForm.getId());
                Activity activity = activityService.get(orderForm.getGoodsId());
                OrderForm mainOrder = orderFormService.get(orderForm.getId());
                if (OrderStatus.ORDER_STATUS_HAVE_PAID.getCode().equals(mainOrder.getStatus())) {
                    sendCode(mainOrder);

                    try {
                        StatisticsInput input = new StatisticsInput();
                        input.setOrderId(orderForm.getId());
                        input.setApplyId(memberAct.getId());
                        input.setPayment(orderForm.getPayment());
                        input.setDistributorTargetId(activity.getId());
                        distributorBizService.dealActivityDistribution(input, memberAct.getMemberId(), new Function() {
                            @Nullable
                            @Override
                            public Object apply(@Nullable Object input) {
                                if (OrderType.ORDER_COURSE.getCode().equals(orderForm.getType())) {
                                    // 插入分销佣金记录
                                    new Thread(() -> {
                                        try {
                                            brokerageBizService.insertBrokerageItem(memberAct.getId(), activity.getId(), BrokerageItem.TYPE_COURSE, memberAct.getMemberId());
                                        } catch (Exception e) {
                                            logger.error("插入分销佣金记录异常", e);
                                        }
                                    }).start();
                                }
                                return null;
                            }
                        });
                    } catch (Exception e) {
                        logger.error("活动/课程支付统计分销数据异常", e);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("支付回调统计异常：orderForm：{}", e, JSONObject.toJSONString(orderForm));
        }
    }


    /**
     * 支持订单支付成功回调
     *
     * @param orderForm 订单信息
     */
    @Transactional
    public void paySupport(OrderForm orderForm) {

        //修改支持状态
        Support support = supportService.findByOrderId(orderForm.getId());
        support.setPayStatus(SUPPORT_IS_PAY);
        supportService.update(support);

        //更改众筹
        Project project = projectService.get(support.getProjectId());
        logger.info("更改众筹project:" + project.toString());
        if (null != project.getRefundState() && !YesNoStatus.YES.getCode().equals(project.getRefundState())) {
            project.setRefundState(YesNoStatus.YES.getCode());
            logger.info("project*****:" + project.toString());
        }

        //最后支持时间
        Date now = DateUtils.getTodayDate();
        project.setLastSupportDate(now);
        logger.info("projectd.getid:" + project.getId() + "setLastSupportDate:" + project.getLastSupportDate());
        //支持前百分比
        int beforePercent = this.getPercent(project);

        TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
        int favorerNum = project.getFavorerNum() + 1;
        float actualAmount = supportService.sumByProjectId(project.getId());

        //实时已筹集金额
        project.setRealTimeAmount(actualAmount);
        //已筹金额是否大于目标金额
        actualAmount = actualAmount > project.getTargetAmount() ? project.getTargetAmount() : actualAmount;
        //project.setFavorerNum(favorerNum);
        project.setActualAmount(actualAmount);

        //更改项目
        Activity activity = activityService.get(targetProject.getTargetId());

        //如果众筹成功
        boolean isSueccess = projectService.isSuccess(project.getTargetAmount(), project.getActualAmount());
        if ((!project.getIsSuccess().equals(Constant.IS_SUCCESS)) && isSueccess) {
            //修改众筹主订单
            OrderForm mainOrder = orderFormService.get(targetProject.getOrderId());
            this.payOrder(mainOrder, null, PaymentWay.CROWD_FUND_PAY.getCode());
            project.setIsSuccess(Constant.IS_SUCCESS);

            //判断是否是多场活动
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
            logger.info("crowdfundEvent::" + crowdfundEvent.toString());
            if (YesNoStatus.NO.getCode() == crowdfundEvent.getIsMultiple()) {
                // 商品正在众筹人数减
                activity.setCrowdfundedNum(activity.getCrowdfundedNum() + 1);
                Integer beCrowdfundNum = activity.getBeCrowdfundNum() - 1 <= 0 ? 0 : activity.getBeCrowdfundNum() - 1;
                activity.setBeCrowdfundNum(beCrowdfundNum);
            }

            //更新成功数
            memberCopartnerDetailBizService.updateSuccess(project.getId());

            //更新联合发起统计
            try {
                logger.info("众筹信息", project);
                distributorCountService.countSuccessNum(project.getId());
            } catch (Exception e) {
                logger.error("更新联合发起统计异常", e);
            }
        }
        projectService.update(project);
        logger.info("projectd.getid:" + project.getId() + "setLastSupportDate:" + project.getLastSupportDate());
        //支持后百分比
        int afterPercent = this.getPercent(project);

        int actFavorerNum = activity.getFavorerNum() + 1;
        activity.setFavorerNum(actFavorerNum);

        activity.setOrderNum(getActivityOrderNum(activity.getOrderNum()));
        activity.setTotalMoney(getActivityTotalMoney(activity.getTotalMoney(), orderForm.getPayment()));

        activityService.update(activity);


        // 众筹者
        Member crowdfundMember = memberService.get(project.getAuthorId());

        // 支持者
        Member supportMember = memberService.get(support.getFavorerId());

        // 项目发布者
        MemberGroup orgMember = memberGroupService.get(activity.getMember());

        try {
            projectBizService.doCrowdRank(afterPercent, beforePercent, activity, support, project);
        } catch (Exception e) {
            logger.error("保存众筹排名异常", e);
        }
        try {
            messageOrderBizService.projectGradationSend(project, beforePercent, afterPercent, activity, crowdfundMember, orgMember);
        } catch (Exception e) {
            logger.error("众筹成功消息推送异常", e);
        }
        ////付款类型：0为普通众筹，1为直接付款众筹',
        if (project.getPayType() == 0) {

            try {
                messageOrderBizService.supportWechatSend(orderForm, project, supportMember, crowdfundMember, orgMember);
            } catch (Exception e) {
                logger.error("支持消息推送异常：projectId-" + project.getId() + "，supportId-" + support.getId(), e);
            }

            //在微信公众号上给支持者推送支持海报
            final String projectId = project.getId();
            final String orderMemberId = orderForm.getMemberId();
            final String activityMemberId = activity.getMember();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        logger.info("开始推送支持海报");
                        messageOrderBizService.supportersPostersSend(projectId, orderMemberId, activityMemberId, String.valueOf(orderForm.getPayment()));
                        logger.info("支持海报推送完成");
                    } catch (Exception e) {
                        logger.error("推送支持者海报失败", e);
                    }
                }
            }).start();
        }


        try {
            memberMerchantDetailBizService.updateOrderNum(activity.getMember(), orderForm.getPayment());
        } catch (Exception e) {
            logger.error("实时更新机构订单统计数异常", e);
        }


        //机构用户
        PartnerMember partnerMember = new PartnerMember();
        partnerMember.setPartnerId(activity.getMember());
        partnerMember.setMemberId(orderForm.getMemberId());
        partnerMemberService.getSet(partnerMember);

        /*try {
            memberPersonalCountBizService.updateCrowdfundMoney(activity.getMember(), project.getAuthorId(), orderForm.getPayment(), true);
        } catch (Exception e) {
            logger.error("实时更新众筹报名金额异常", e);
        }

        try {
            memberPersonalCountBizService.updateSupportMoney(activity.getMember(), orderForm.getMemberId(), orderForm.getPayment(), true);
        } catch (Exception e) {
            logger.error("实时更新个人统计支持金额异常", e);
        }*/

        // 实时统计个人数据后, 马上校验该机构下的该用户和该用户支持的人的数据
        try {
            memberPersonalCountBizService.countOne(partnerMember);

            PartnerMember projectPartnerMemberCount = partnerMemberService.findByPartnerAndMember(activity.getMember(), project.getAuthorId());
            memberPersonalCountBizService.countOne(projectPartnerMemberCount);
        } catch (Exception e) {
            logger.error("实时更新个人统计支持后矫正异常", e);
        }

        Member member = memberService.get(support.getFavorerId());
    }

    public List<OrderOutput> listOrderOutput2(MemberAct memberAct, Map<String, Object> params, Page page) {
        List<MemberAct> dbList = memberActService.listPageTwo(memberAct, params, page);
        if (!CollectionUtils.isEmpty(dbList)) {
            List<OrderOutput> orderOutputList = LangUtils.transform(dbList, input -> {
                OrderOutput orderOutput = new OrderOutput();
                orderOutput.setId(input.getId());
                orderOutput.setStatus(input.getCheckStatus());
                orderOutput.setUnit(1);
                orderOutput.setPayment(input.getPayment());
                Activity activity = activityService.get(input.getActId());
                if (null != activity) {
                    //活动信息
                    orderOutput.setDescription(activity.getTitle());
                    orderOutput.setLogo(activity.getPic());
                    orderOutput.setStartTime(activity.getStartTime());
                    orderOutput.setEndTime(activity.getEndTime());
                    orderOutput.setGoodsId(activity.getId());
                }
                return orderOutput;
            });
            return orderOutputList;
        }
        return Collections.EMPTY_LIST;
    }

    /**
     * 获取众筹百分比
     *
     * @param project 众筹项目
     * @return 百分比
     */
    public int getPercent(Project project) {
        //支持前百分比
        double percent = BigDecimalUtils.div(project.getActualAmount(), project.getTargetAmount(), 2);
        int intPercent = BigDecimalUtils.amplify2int(percent, 1);
        return intPercent;
    }

    /**
     * 根据订单获取活动订单详情
     *
     * @param orderForm
     * @return
     */
    public ActOrderDetailOutput outputByOrderForm(OrderForm orderForm) throws Exception {
        //验证活动订单关联的商品数据是否存在
        Activity activity = activityService.get(orderForm.getGoodsId());
        if (null == activity) {
            throw new BusinessException(PartyCode.ORDER_FORM_GOODS_NOT_EXIT, "订单数据错误，商品或活动不存在");
        }

        //输出活动订单信息
        ActOrderDetailOutput output = ActOrderDetailOutput.transform(orderForm);
        //设置城市
        City city = cityService.get(activity.getCityId());
        if (null != city) {
            output.setCityName(city.getName());
        }
        output.setAreaName(activity.getArea());
        output.setPlace(activity.getPlace());

        //设置活动信息
        output.setDescription(activity.getTitle());
        output.setLogo(activity.getPic());
        output.setStartTime(activity.getStartTime());
        output.setEndTime(activity.getEndTime());
        //设置活动报名信息
        MemberAct dbMemberAct = memberActService.getMyAct(orderForm.getMemberId(), activity.getId());
        if (null != dbMemberAct) {
            output.setMeberActId(dbMemberAct.getId());
            output.setActStatus(dbMemberAct.getCheckStatus());
            output.setCounterName(dbMemberAct.getCounterfoilName());
            output.setPayment(dbMemberAct.getPayment());
            output.setCounterType(dbMemberAct.getCounterfoilType());
        }


        //获取活动提供方
        MemberGroup member = memberGroupService.get(activity.getMember());
        if (null != member) {
            output.setThirdPartyName(member.getRealname());
            output.setTelephone(member.getMobile());
        }

        //设置核销码
        GoodsCoupons goodsCoupons = new GoodsCoupons();
        goodsCoupons.setGoodsId(activity.getId());
        goodsCoupons.setMemberId(orderForm.getMemberId());
        goodsCoupons.setStatus(YesNoStatus.YES.getCode());

        List<GoodsCoupons> goodsCouponseslist = goodsCouponsService.list(goodsCoupons);

        List<String> list = new ArrayList<>();
        for (int i = 0; i < goodsCouponseslist.size(); i++) {
            list.add(goodsCouponseslist.get(i).getVerifyCode());
        }
        output.setConsumerCode(list);
        return output;
    }

    /**
     * 根据活动报名获取活动订单详情
     *
     * @param memberAct
     * @return
     */
    public ActOrderDetailOutput outputByMemberAct(MemberAct memberAct) throws Exception {
        // 验证活动订单关联的商品数据是否存在
        Activity activity = activityService.get(memberAct.getActId());
        if (null == activity) {
            throw new BusinessException(PartyCode.ORDER_FORM_GOODS_NOT_EXIT, "订单数据错误，商品或活动不存在");
        }

        OrderForm orderForm = new OrderForm();
        orderForm.setStatus(memberAct.getCheckStatus());
        orderForm.setUnit(1);
        orderForm.setPayment(memberAct.getPayment());
        orderForm.setCreateDate(memberAct.getCreateDate());

        // 输出活动订单信息
        ActOrderDetailOutput output = ActOrderDetailOutput.transform(orderForm);

        // 设置城市
        City city = cityService.get(activity.getCityId());
        if (null != city) {
            output.setCityName(city.getName());
        }
        output.setAreaName(activity.getArea());
        output.setPlace(activity.getPlace());
        output.setGoodsId(activity.getId());

        // 设置活动信息
        output.setDescription(activity.getTitle());
        output.setLogo(activity.getPic());
        output.setStartTime(activity.getStartTime());
        output.setEndTime(activity.getEndTime());
        // 设置活动报名信息
        output.setMeberActId(memberAct.getId());
        output.setActStatus(memberAct.getCheckStatus());
        output.setCounterName(memberAct.getCounterfoilName());
        output.setPayment(memberAct.getPayment());
        output.setCounterType(memberAct.getCounterfoilType());

        MemberGroup member = memberGroupService.get(activity.getMember());
        if (null != member) {
            output.setThirdPartyName(member.getRealname());
            output.setTelephone(member.getMobile());
        }

        // 设置核销码
        GoodsCoupons goodsCoupons = new GoodsCoupons();
        goodsCoupons.setGoodsId(activity.getId());
        goodsCoupons.setMemberId(memberAct.getMemberId());
        goodsCoupons.setStatus(YesNoStatus.YES.getCode());

        List<GoodsCoupons> goodsCouponseslist = goodsCouponsService.list(goodsCoupons);

        List<String> list = new ArrayList<>();
        for (int i = 0; i < goodsCouponseslist.size(); i++) {
            list.add(goodsCouponseslist.get(i).getVerifyCode());
        }
        output.setConsumerCode(list);

        if (null != output.getActStatus()) {
            switch (output.getActStatus()) {
                case 0: // 审核中
                    output.setStatus(OrderStatus.ORDER_STATUS_IN_REVIEW.getCode());
                    break;
                case 1: // 待支付
                    output.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                    break;
                case 2: // 审核拒绝
                    if (StringUtils.isNotEmpty(memberAct.getOrderId())) {
                        OrderForm order = orderFormService.get(memberAct.getOrderId());
                        if (order != null && order.getPayment().equals(memberAct.getPayment())) {
                            output.setStatus(OrderStatus.ORDER_STATUS_REFUND.getCode());
                        } else {
                            output.setStatus(OrderStatus.ORDER_STATUS_OTHER.getCode());
                        }
                    } else {
                        output.setStatus(OrderStatus.ORDER_STATUS_OTHER.getCode());
                    }
                    break;
                case 3: // 已支付
                    output.setStatus(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode());
                    break;
                case 4: // 已取消
                    output.setStatus(OrderStatus.ORDER_STATUS_OTHER.getCode());
                    break;
            }
        }
        return output;
    }

    /**
     * 活动，众筹已支付的订单总额
     *
     * @return
     */
    public Double getOrderTotal(boolean isTxz, String memberId) {
        OrderForm orderForm = new OrderForm();
        orderForm.setStatus(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode()); // 已支付
        orderForm.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        Map<String, Object> params = new HashMap<String, Object>();

        if (isTxz) {
            Set<String> merchants = MerchantUtil.getTxzMerchants();
            params.put("txzMerchantId", merchants);
        }

        params.put("isCrowdfund", 0);
        params.put("payment", 0);
        List<String> initiatorIds = memberGroupService.getChildWithMy(memberId);
        params.put("initiatorIds", initiatorIds);
        return orderFormService.getTotalPayment(orderForm, params);
    }

    /**
     * 累计订单数
     *
     * @param orderNum 原始订单数
     * @return
     */
    private Long getActivityOrderNum(Long orderNum) {
        // 累计订单数
        Long newOrderNum = orderNum == null ? 0L : orderNum;
        newOrderNum = newOrderNum + 1;
        return newOrderNum;
    }

    /**
     * 累计资金
     *
     * @param totalMoney 原始资金
     * @param payment    订单金额
     * @return
     */
    private Double getActivityTotalMoney(Double totalMoney, Float payment) {
        // 累计资金数
        Double newTotalMoney = totalMoney == null ? 0d : totalMoney;
        newTotalMoney = BigDecimalUtils.add(newTotalMoney, payment);
        newTotalMoney = BigDecimalUtils.round(newTotalMoney, 2);
        return newTotalMoney;
    }


    /***
     * 阶段众筹成功  维护project_gradation中的useTime字段
     * @param eventGradation
     * @param project
     */
    public void updateProjectGradation(EventGradation eventGradation, Project project) {
        /** 找到正在进行的projectGradation*/
        ProjectGradation ongoingProjectGradation = projectGradationService.
                getByEventGradationId(eventGradation.getId(), project.getId());
        /** 根据当前阶段主题找到上一阶段主题*/
        EventGradation eventGradationOnA = eventGradationService.
                getTheNextGradation(eventGradation);
        ongoingProjectGradation.setSuccessTime(new Date());
        long now = DateUtils.getTodayDate().getTime();
        if (eventGradationOnA == null) {
            long createDate = project.getCreateDate().getTime();
            ongoingProjectGradation.setUseTime(now - createDate);
        } else {
            /** 找到上一个projectGradation*/
            ProjectGradation projectGradation = projectGradationService.
                    getByEventGradationId(eventGradationOnA.getId(), project.getId());
            if (projectGradation == null) {
                long createDate = project.getCreateDate().getTime();
                ongoingProjectGradation.setUseTime(now - createDate);
            } else {
                long createDate = eventGradationOnA.getEndTime().getTime();
                long useTime = now - createDate;
                if (useTime < 0) {
                    useTime = 6000;
                }
                ongoingProjectGradation.setUseTime(useTime);
            }
        }
        projectGradationService.update(ongoingProjectGradation);


        //众筹成功推送
        try {
            TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
            projectMessageService.gradationCrowfundSuccessSend(targetProject.getOrderId(), project.getId(), eventGradation);
        } catch (Exception e) {
            logger.info("支付回调__多场活动众筹成功推送异常", e);
        }

        logger.info("ongoingProjectGradation：" + ongoingProjectGradation.toString());
    }


    /***
     * 多场活动支付回调更新
     * @param orderForm
     */
    public void updateMultipleActivity(OrderForm orderForm) {

        long start,end;
        start = System.currentTimeMillis();
        // 众筹支持订单
        if (OrderType.ORDER_CROWD_FUND.getCode().equals(orderForm.getType())) {
            Support support = supportService.findByOrderId(orderForm.getId());
            Project project = projectService.get(support.getProjectId());
            Double actualAmount = supportService.sumByProjectId(project.getId()).doubleValue();
            project.setActualAmount(actualAmount.floatValue());
            TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
            Activity activity = activityService.get(targetProject.getTargetId());
            //判断是否是多场活动
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
            logger.info("crowdfundEvent::" + crowdfundEvent.toString());
            if (YesNoStatus.YES.getCode().equals(crowdfundEvent.getIsMultiple())) {
                logger.info("多场活动支付回调更新数据开始");
                /** 根据projectId 找到当前众筹者正在众筹哪个阶段*/
                EventGradation eventGradation = eventGradationService.getOngoingGradation(project.getId());
                automaticInto(eventGradation,project,activity);
            }
            logger.info("多场活动支付回调更新结束======"+orderForm.getId());

        }
        end = System.currentTimeMillis();
        logger.info(orderForm.getId()+"多场活动支付回调更新时间 :{}", (end - start) + "(ms)");

    }


    /***
     * 多场活动自动转入下个阶段/支付回调 维护zc_project_info,zc_project_gradation
     * @param ongoingGradation
     * @param project
     */
    public void automaticInto(EventGradation ongoingGradation,Project project,Activity activity) {
        ProjectInfoGradation byProjectId = projectInfoGradationService.findByProjectId(project.getId());
        ProjectGradation byEventGradationId = projectGradationService.getByEventGradationId(ongoingGradation.getId(), project.getId());
        /** 找到当前系统阶段之前所有成功阶段的目标金额之和*/
        Double effectiveAmount = projectGradationService.getEffectiveAmount(ongoingGradation.getEndTime(), project.getId());
        /** 累计金额减去前面阶段的众筹成功金额等于剩余金额*/
        double surplus = BigDecimalUtils.sub(project.getActualAmount().doubleValue(), effectiveAmount);
        surplus = BigDecimalUtils.round(surplus, 2);
        /** 如果剩余金额大于等于当前系统阶段的目标金额，那说明当前阶段已经成功了*/
        if (surplus >= ongoingGradation.getPrice()){

            if (effectiveAmount < 0.01) {
                // 商品正在众筹人数减
                activity.setCrowdfundedNum(activity.getCrowdfundedNum() + 1);
                Integer beCrowdfundNum = activity.getBeCrowdfundNum() - 1 <= 0 ? 0 : activity.getBeCrowdfundNum() - 1;
                activity.setBeCrowdfundNum(beCrowdfundNum);
                activityService.update(activity);
            }

            /** 获取当前系统阶段之后的阶段*/
            List<EventGradation> eventGradationList = eventGradationService.getAfterEventGradations(ongoingGradation);
            /** 目标金额*/
            double targetMoney = ongoingGradation.getPrice();
            if (eventGradationList.size() > 0) {
                for (EventGradation gradation : eventGradationList) {
                    ProjectGradation projectGradation = projectGradationService.
                            getByEventGradationId(gradation.getId(), project.getId());
                    byProjectId.setProjectGradationId(projectGradation.getId());
                    projectInfoGradationService.update(byProjectId);
                    this.updateProjectGradation(ongoingGradation, project);
                    //报名推送
                    try {
                        projectMessageService.gradationApplySend(project.getId(), project.getAuthorId(),
                                activity.getId(), DistributorRelationType.CROWDFUND_REPRESENT.getCode(), gradation);
                    } catch (Exception e) {
                        logger.info("支付回调__多场活动阶段报名异常", e);
                    }
                    targetMoney = BigDecimalUtils.add(targetMoney, gradation.getPrice());
                    targetMoney = BigDecimalUtils.round(targetMoney, 2);
                    surplus = BigDecimalUtils.sub(surplus, targetMoney);
                    surplus = BigDecimalUtils.round(surplus, 2);
                    if (surplus < 0) {
                        break;
                    }
                    /** 如果最后一个阶段都筹满了 那update最后一个阶段的project_gradation*/
                    EventGradation eventGradation = eventGradationList.get(eventGradationList.size() - 1);
                    if (eventGradation.getId().equals(gradation.getId())) {
                        this.updateProjectGradation(gradation, project);
                        project.setIsSuccess(Constant.IS_SUCCESS);
                        projectService.update(project);
                    }
                    ongoingGradation = gradation;
                }
                logger.info("多场活动支付回调更新数据结束11");
            } else {
                /** 说明是最后一场成功了*/
                this.updateProjectGradation(ongoingGradation, project);
                project.setIsSuccess(Constant.IS_SUCCESS);
                projectService.update(project);
                byProjectId.setProjectGradationId(byEventGradationId.getId());
                projectInfoGradationService.update(byProjectId);
            }
            if (project.getPayType() == 0) {

                //在微信公众号上给众筹者推送成功海报
                new Thread(() -> {
                    try {
                        messageOrderBizService.raiseSuccessfulPostersSend(project.getId(),
                                project.getAuthorId(), activity.getMember());
                    } catch (Exception e) {
                        logger.error("推送成功海报失败", e);
                    }
                }).start();
            }

        }else {
            byProjectId.setProjectGradationId(byEventGradationId.getId());
            projectInfoGradationService.update(byProjectId);
        }

    }


    /***不需要推送海报，不需要推送报名
     * 多场活动自动转入下个阶段/定时器，个人众筹页 维护zc_project_info,zc_project_gradation
     * @param ongoingGradation
     * @param project
     */
    public void automaticShift(EventGradation ongoingGradation,Project project,Activity activity) {
        ProjectInfoGradation byProjectId = projectInfoGradationService.findByProjectId(project.getId());
        ProjectGradation byEventGradationId = projectGradationService.getByEventGradationId(ongoingGradation.getId(), project.getId());
        /** 找到当前系统阶段之前所有成功阶段的目标金额之和*/
        Double effectiveAmount = projectGradationService.getEffectiveAmount(ongoingGradation.getEndTime(), project.getId());
        /** 累计金额减去前面阶段的众筹成功金额等于剩余金额*/
        double surplus = BigDecimalUtils.sub(project.getActualAmount().doubleValue(), effectiveAmount);
        surplus = BigDecimalUtils.round(surplus, 2);
        /** 如果剩余金额大于等于当前系统阶段的目标金额，那说明当前阶段已经成功了*/
        if (surplus >= ongoingGradation.getPrice()){
            if (effectiveAmount < 0.01) {
                // 商品正在众筹人数减
                activity.setCrowdfundedNum(activity.getCrowdfundedNum() + 1);
                Integer beCrowdfundNum = activity.getBeCrowdfundNum() - 1 <= 0 ? 0 : activity.getBeCrowdfundNum() - 1;
                activity.setBeCrowdfundNum(beCrowdfundNum);
                activityService.update(activity);
            }

            /** 获取当前系统阶段之后的阶段*/
            List<EventGradation> eventGradationList = eventGradationService.getAfterEventGradations(ongoingGradation);
            /** 目标金额*/
            double targetMoney = ongoingGradation.getPrice();
            if (eventGradationList.size() > 0) {
                for (EventGradation gradation : eventGradationList) {
                    ProjectGradation projectGradation = projectGradationService.
                            getByEventGradationId(gradation.getId(), project.getId());
                    byProjectId.setProjectGradationId(projectGradation.getId());
                    projectInfoGradationService.update(byProjectId);
                    this.updateProjectGradation(ongoingGradation, project);
                    targetMoney = BigDecimalUtils.add(targetMoney, gradation.getPrice());
                    targetMoney = BigDecimalUtils.round(targetMoney, 2);
                    surplus = BigDecimalUtils.sub(surplus, targetMoney);
                    surplus = BigDecimalUtils.round(surplus, 2);
                    if (surplus < 0) {
                        break;
                    }
                    /** 如果最后一个阶段都筹满了 那update最后一个阶段的project_gradation*/
                    EventGradation eventGradation = eventGradationList.get(eventGradationList.size() - 1);
                    if (eventGradation.getId().equals(gradation.getId())) {
                        this.updateProjectGradation(gradation, project);
                        project.setIsSuccess(Constant.IS_SUCCESS);
                        projectService.update(project);
                    }
                    ongoingGradation = gradation;
                }
                logger.info("多场活动支付回调更新数据结束11");
            } else {
                /** 说明是最后一场成功了*/
                this.updateProjectGradation(ongoingGradation, project);
                project.setIsSuccess(Constant.IS_SUCCESS);
                projectService.update(project);
                byProjectId.setProjectGradationId(byEventGradationId.getId());
                projectInfoGradationService.update(byProjectId);
            }
            if (project.getPayType() == 0) {
                //生成海报
                new Thread(() -> {
                    try {
                        projectBizService.paintProjectPoster(project.getId());
                    } catch (Exception e) {
                        logger.error("推送成功海报失败", e);
                    }
                }).start();
            }
         }else {
            byProjectId.setProjectGradationId(byEventGradationId.getId());
            projectInfoGradationService.update(byProjectId);
        }

    }

    /**
     * @param orderForm  订单
     * @param paymentWay 支付类型
     * @return
     * @Author yifeng
     * @Description 修改订单状态
     * @Date 12:03 2019/4/10
     **/
    public void updateOrderStatus(OrderForm orderForm, Object object, Integer paymentWay) {
        orderForm.setIsPay(PaymentState.IS_PAY.getCode());
        orderForm.setPaymentWay(paymentWay);
        orderForm.setStatus(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode());
        orderForm.setUpdateDate(new Date());
        // 保存支付流水，修改订单支付信息
        if (null != object) {
            orderTradeBizService.save(orderForm, object, paymentWay);
        }
        orderFormService.update(orderForm);
    }
}


